package org.example.utils;

import com.alibaba.fastjson2.JSON;
import org.springframework.util.CollectionUtils;

import java.util.List;

public  class ConverterUtil {

    /**
     * 将一个对象转换为目标对象
     * @param source 待转换的原对象
     * @param target 目标对象
     * @return
     * @param <T>
     */
    public static <T> T convert(Object source, Class<T> target){
        if(source==null){
            return null;
        }
        if(target==null){
            throw new NullPointerException("目标对象的class为空");
        }
        try{
            String jsonStr = JSON.toJSONString(source);
            return JSON.parseObject(jsonStr,target);
        }catch (Exception e){
            throw  new RuntimeException("Converter转换异常");

        }
    }

    /**
     * 将一个对象集合转换为目标对象集合
     * @param source
     * @param target
     * @return
     * @param <T>
     */
    public static <T> List<T> convertArray(List<?> source, Class<T> target) {
        if (CollectionUtils.isEmpty(source)) {
            return null;
        }
        if (target == null) {
            throw new NullPointerException("目标对象的class为空");
        }
        try{
            String jsonStr = JSON.toJSONString(source);
            return JSON.parseArray(jsonStr,target);
        }catch (Exception e){
            throw  new RuntimeException("Converter转换异常");

        }
    }

}
